package org.i9.slb.platform.anseko.provider.repository;

import org.i9.slb.platform.anseko.provider.dto.CommandDispatchDto;
import org.i9.slb.platform.anseko.provider.repository.mapper.CommandDispatchRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.UUID;

/**
 * 命令调度dao
 *
 * @author R12
 * @date 2018年9月4日 10:50:09
 */
@Repository
public class CommandDispatchRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存命令调度信息
     *
     * @param commandDispatchDto
     */
    public void insertCommandDispatch(CommandDispatchDto commandDispatchDto) {
        String sql = "INSERT INTO t_command_dispatch (id, commandGroupId, simulatorId, success, startDate) VALUES (?, ?, ?, 0, NOW())";
        jdbcTemplate.update(sql,
                new Object[]{
                        UUID.randomUUID().toString(),
                        commandDispatchDto.getCommandGroupId(),
                        commandDispatchDto.getSimulatorId()
                });
    }

    /**
     * 更新命令调度状态
     *
     * @param commandGroupId
     * @param success
     */
    public void updateCommandDispatchEndTime(String commandGroupId, int success) {
        String sql = "UPDATE t_command_dispatch SET endDate = NOW(), success = ? WHERE commandGroupId = ?";
        jdbcTemplate.update(sql, new Object[]{success, commandGroupId});
    }

    /**
     * 获取模拟器命令调度列表
     *
     * @param simulatorId
     * @return
     */
    public List<CommandDispatchDto> queryCommandDispatchDtos(String simulatorId) {
        String sql = "SELECT commandGroupId, simulatorId, startDate, endDate, success FROM t_command_dispatch WHERE simulatorId = ?";
        List<CommandDispatchDto> commandDispatchDtos = this.jdbcTemplate.query(sql, new Object[]{simulatorId}, new CommandDispatchRowMapper());
        return commandDispatchDtos;
    }

    /**
     * 获取命令调度信息
     *
     * @param commandGroupId
     * @return
     */
    public CommandDispatchDto queryCommandDispatchDto(String commandGroupId) {
        String sql = "SELECT commandGroupId, simulatorName, startDate, endDate, success FROM t_command_dispatch WHERE commandGroupId = ?";
        List<CommandDispatchDto> commandDispatchDtos = this.jdbcTemplate.query(sql, new Object[]{commandGroupId}, new CommandDispatchRowMapper());
        if (commandDispatchDtos.isEmpty()) {
            return null;
        }
        return commandDispatchDtos.get(0);
    }
}
